package com.bigwolf.pe.controller;

import com.bigwolf.pe.constant.CacheConstants;
import com.bigwolf.pe.constant.Constants;
import com.bigwolf.pe.core.redis.RedisCache;
import com.bigwolf.pe.utils.AjaxResult;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class SysCaptchaController {
    @Autowired
    private RedisCache redisCache;
    /**
     * 验证码宽度
     */
    Integer CAPTCHA_WIDTH = 130;
    /**
     * 验证码高度
     */
    Integer CAPTCHA_HEIGHT = 48;

    /**
     * 验证码长度
     */
    Integer CAPTCHA_LENGTH = 4;

    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletRequest request, HttpServletResponse response) {
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        Map<String, String> captchaMap = new HashMap<>();

        SpecCaptcha specCaptcha = new SpecCaptcha(CAPTCHA_WIDTH,CAPTCHA_HEIGHT,CAPTCHA_LENGTH);
        String codeValue = specCaptcha.text().toLowerCase();
        specCaptcha.out(os);

        redisCache.setCacheObject(verifyKey, codeValue, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.getEncoder().encodeToString(os.toByteArray()));
        return ajax;
    }
}
